define(['websocketbridge'], function(websocketbridge) {
  var that = {};
  var webSocketBridge;
  var socketUrl;
  var token = window.localStorage.getItem('token');

  // 初始化
  var initSocket = function(ids, type) {
    var type = type || 'chart';
    // 初始化socket时关闭之前的
    if (webSocketBridge) {
      that.closeSocket();
    };

    // console.log('initSocket');
    var idStr = Array.isArray(ids) ? ids.join(',') : ids;
    socketUrl = 'ws://' + window.baseUrl + '/' + type + '-' + idStr;
    // socketUrl = 'ws://106.38.67.196:8000/' + type + '-' + idStr;
    //  socketUrl = 'ws://192.168.1.55:8000/chart-' + idStr;
    webSocketBridge = new websocketbridge.WebSocketBridge();
    webSocketBridge.connect(socketUrl);
  };

  // 接收消息
  var onMessage = function(callback) {
    webSocketBridge.listen(function(action, stream) {
      callback && callback(action);
    });
  };

  // 发送消息
  var sendMessage = function(data) {
    webSocketBridge.send({
      token: token,
      data: data
    });
  };

  // 断开连接
  var closeSocket = function() {
    webSocketBridge && webSocketBridge.socket.close();
  };

  that.initSocket = initSocket;
  that.onMessage = onMessage;
  that.sendMessage = sendMessage;
  that.closeSocket = closeSocket;
  return that;
})
